'use strict';
import React from "react";
import {StyleSheet, Text, TextInput, TouchableOpacity, View} from "react-native";
import NavigationBar from "../../component/navigation/NavigationBar";
import Container from "../../component/common/Container";
import {inject, observer} from "mobx-react";
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view";
import Button from "../../component/common/Button";
import ImageView from "../../component/common/ImageView";
import ImagePickerManager from "../../config/manager/ImagePickerManager";

@inject('loginStore', 'mineStore', 'taskStore')
@observer
class PublishVideo extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.item = this.params.item || {};
        this.state = {
            coverImg: this.item.cover_url,
            videoData: this.item.video_key || '',
            subs: this.item.subs || '',
            sub_title: '',
            category: [],
        };
        this.articleContent = this.item.information_content;
        this.articleTitle = this.item.information_title;
    }

    doOnCallBack = () => {
        let {onCallBack} = this.params;
        onCallBack && onCallBack();
        RouterHelper.goBack();
    };

    componentDidMount() {
        this.getCategory();
    }

    getCategory = async () => {
        let {subs, sub_title} = this.state;
        let url = ServicesApi.ARTICLE_CATEGORY;
        let result = await Services.get(url);
        if (result.code === StatusCode.SUCCESS_CODE) {
            result.data.forEach((item) => {
                if (item.dic_code == subs) {
                    sub_title = item.dic_name;
                }
            });
            // console.log('sub_title---->', sub_title);
            this.setState({
                sub_title,
                category: result.data,
            });
        }
    };

    _onPressPublish = async () => {
        let {subs} = this.state;
        const {loginStore, mineStore, taskStore} = this.props;
        // console.log('发布视频');
        if (!this.articleTitle) {
            ToastManager.show('请填写标题');
            return;
        }
        if (!subs) {
            ToastManager.show('请选择文章分类');
            return;
        }
        if (!this.articleContent) {
            ToastManager.show('视频详情不能为空');
            return;
        }
        if (!this.state.coverImg) {
            ToastManager.show('请选择视频封面');
            return;
        }
        if (!this.state.videoData) {
            ToastManager.show('请上传视频文件');
            return;
        }
        const data = {
            author_id: global.secretKey,
            author_name: loginStore.getUserInfo.user_nickname,
            information_title: this.articleTitle,
            information_content: this.articleContent,
            article_type: 2,
            subs,
            data_type: 'local',
            audit_status: 'wait',
            station: 'app',
            cover_url: this.state.coverImg,
            // videoVOs: JSON.stringify([this.state.videoData]),
            video_key: this.state.videoData,
        };
        const result = await Services.post(ServicesApi.PUBLISH_INFORMATION, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.show('发布成功!');
            await taskStore.saveTask('publish');
            this.doOnCallBack();
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };

    _onPressEdit = async () => {
        const {loginStore, mineStore} = this.props;
        let {subs} = this.state;
        // console.log('编辑视频');
        if (!this.articleTitle) {
            ToastManager.show('请填写标题');
            return;
        }
        if (!subs) {
            ToastManager.show('请选择文章分类');
            return;
        }
        if (!this.articleContent) {
            ToastManager.show('视频详情不能为空');
            return;
        }
        if (!this.state.coverImg) {
            ToastManager.show('请选择视频封面');
            return;
        }
        if (!this.state.videoData) {
            ToastManager.show('请上传视频文件');
            return;
        }
        const data = {
            information_id: this.item.information_id,
            author_id: global.secretKey,
            author_name: loginStore.getUserInfo.user_nickname,
            information_title: this.articleTitle,
            information_content: this.articleContent,
            article_type: 2,
            subs,
            data_type: 'local',
            station: 'app',
            audit_status: 'wait',
            cover_url: this.state.coverImg,
            // videoVOs: JSON.stringify([this.state.videoData]),
            video_key: this.state.videoData,
        };
        const result = await Services.post(ServicesApi.PUBLISH_INFORMATION, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.show('修改成功!');
            this.doOnCallBack();
            // const requestData = {
            //     page: 1,
            //     limit: 10,
            //     author_id: global.secretKey,
            //     audit_status: 'wait',
            // };
            // await mineStore.requestMyPublish(0,requestData);
            // RouterHelper.goBack();
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };

    _onPressSelectVideo = async () => {
        // const result = await ImagePickerManager.showVideoPicker({isCamera: false, MinSecond: 5, videoCount: 1});
        let params = {
            mediaType: 'video',
        };
        let result = await ImagePickerManager.showImagePicker(params);
        // console.log('选择视频返回------------>', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let resources = [result.data];
            ToastManager.showCustom('视频上传中...', 599999);
            let upData = await Services.uploadQiNiu(resources);
            if (upData.code === StatusCode.SUCCESS_CODE) {
                ToastManager.hideCustom();
                ToastManager.success('视频上传成功...');
                // console.log('七牛上传视频成功----------');
                // this.setState({videoData: `${ServicesApi.QI_NIU_LINK}${upData.data[0].key}`});
                this.setState({videoData: `${upData.data[0].key}`});
                // console.log(this.state.videoData);
            } else {
                ToastManager.hideCustom();
                ToastManager.fail('视频上传失败...');
            }
        } else {
            ToastManager.show(result.msg);
        }
    };

    _onPressSelectCategory = () => {
        let {category} = this.state;
        let actions = [];
        category.forEach((item) => {
            let obj = {
                title: item.dic_name,
                onPress: () => this.setState({
                    subs: item.dic_code,
                    sub_title: item.dic_name,
                })
            };
            actions.push(obj);
        });
        let params = {
            title: '分类选择',
            actions,
        };
        ActionsManager.show(params);
    };

    _onPressSelectCover = async () => {
        const result = await ImagePickerManager.showMultipleImagePicker({imageCount: 1});
        // console.log('发帖选择图片返回----------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            const upData = await Services.uploadQiNiu(result.data);
            if (upData.code === StatusCode.SUCCESS_CODE) {
                // console.log('七牛上传封面成功----------');
                this.setState({coverImg: `${upData.data[0].key}`});
                // console.log(this.state.coverImg);
            } else {
                ToastManager.show('上传失败');
            }
        }
    };

    render() {
        let {videoData, coverImg, sub_title} = this.state;
        const {params} = this.props.navigation.state;
        const pageTitle = params.pageTitle || '视频发布';
        return (
            <Container>
                <NavigationBar
                    title={pageTitle}
                />
                <KeyboardAwareScrollView
                    style={styles.contView}
                    keyboardShouldPersistTaps={'handled'}
                >
                    <TextInput
                        placeholder={'请输入标题'}
                        numberOfLines={1}
                        style={styles.titleInput}
                        defaultValue={this.articleTitle}
                        onChangeText={(text) => {
                            this.articleTitle = text
                        }}
                    />
                    <TouchableOpacity
                        onPress={() => this._onPressSelectCategory()}
                        style={styles.coverView}
                    >
                        <Text style={styles.coverText}>分类</Text>
                        <View style={styles.coverImgView}>
                            <Text style={styles.coverImgText}>{sub_title ? sub_title : '选择分类'}</Text>
                            <ImageView
                                style={styles.coverImgIcon}
                                source={Images.icon_arrow_right}
                            />
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity
                        onPress={() => this._onPressSelectCover()}
                        style={styles.coverView}>
                        <Text style={styles.coverText}>视频封面</Text>
                        <View style={styles.coverImgView}>
                            <Text style={styles.coverImgText}>选择图片</Text>
                            <ImageView
                                style={styles.coverImgIcon}
                                source={Images.icon_arrow_right}
                            />
                        </View>
                    </TouchableOpacity>
                    {coverImg && <ImageView
                        resizeMode={'cover'}
                        style={styles.coverImgStyle}
                        source={{uri: coverImg}}
                    />}
                    <View style={[styles.contentItem]}>
                        <Text style={styles.contentItemTitle}>视频详情</Text>
                        <TextInput
                            placeholder={'请输入文章详情'}
                            multiline={true}
                            defaultValue={this.articleContent}
                            style={styles.detailInput}
                            onChangeText={(text) => {
                                this.articleContent = text
                            }}
                        />
                    </View>
                    <TouchableOpacity
                        onPress={() => this._onPressSelectVideo()}
                        style={styles.coverView}>
                        <Text style={styles.coverText}>视频上传</Text>
                        <View style={styles.coverImgView}>
                            <Text
                                style={[styles.coverImgText, {color: this.state.videoData ? '#00ff00' : '#9e9e9e'}]}>{this.state.videoData ? '已选择' : '选择视频'}</Text>
                            <ImageView
                                style={styles.coverImgIcon}
                                source={Images.icon_arrow_right}
                            />
                        </View>
                    </TouchableOpacity>
                    <Text style={styles.videoText}>{this.state.videoData}</Text>
                    <Button
                        title={'发布视频'}
                        onPress={this.item.information_id ? this._onPressEdit : this._onPressPublish}
                        style={styles.buttonStyle}
                        titleStyle={styles.buttonTitle}
                    />
                </KeyboardAwareScrollView>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    contView: {
        paddingHorizontal: 15,
    },
    contentItem: {
        marginTop: 15,
    },
    contentItemTitle: {
        fontSize: 16,
        color: "#333",
        marginBottom: 15,
    },
    titleInput: {
        borderRadius: 3,
        borderWidth: Theme.minPixel,
        borderColor: "#dbdbdb",
        fontSize: FontSize(16),
        color: '#333',
        padding: 10,
        marginTop: 22,
    },
    coverView: {
        padding: 10,
        borderRadius: 3,
        borderWidth: Theme.minPixel,
        borderColor: "#dbdbdb",
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginTop: 14,
    },
    coverText: {
        fontSize: FontSize(16),
        color: "#333",
    },
    coverImgView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    coverImgStyle: {
        marginTop: 15,
        alignSelf: 'center',
        width: SCREEN_WIDTH - 30,
        height: (SCREEN_WIDTH - 30) * 0.6,
    },
    coverImgText: {
        fontSize: FontSize(14),
        color: "#9e9e9e",
    },
    coverImgIcon: {
        width: 9,
        height: 15,
        marginLeft: 9,
    },
    detailInput: {
        textAlignVertical: 'top',
        padding: 10,
        fontSize: 13,
        color: '#333',
        lineHeight: 18,
        borderRadius: 3,
        borderWidth: Theme.minPixel,
        borderColor: "#dbdbdb",
        // marginTop: 31,
        minHeight: 120,
    },

    buttonStyle: {
        marginTop: 30,
        alignSelf: 'center',
        paddingVertical: 10,
        paddingHorizontal: 66,
        backgroundColor: '#ffa64f',
        borderRadius: 3,
        marginBottom: 15,
    },
    buttonTitle: {
        fontSize: FontSize(16),
        color: "#ffffff",
    },
    videoText: {
        fontSize: FontSize(14),
        color: "#9e9e9e",
        marginTop: 15,
    }
});

export default PublishVideo